package xyz.gpgl.erp.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import common.util.base.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import xyz.gpgl.erp.sys.entity.SysUser;
import xyz.gpgl.erp.sys.entity.emeus.SysUserEmeus;
import xyz.gpgl.erp.sys.service.ISysUserService;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class MyUserDetailServiceImpl implements UserDetailsService {
	
	@Autowired
	private ISysUserService iSysUserService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		if(CommonUtil.isEmpty(username)) {
			throw new UsernameNotFoundException("用户不存在！");
		}
		//从数据库查询用户信息
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq(SysUserEmeus.phone, username);
		SysUser userInfo = iSysUserService.getOne(queryWrapper);
		if (CommonUtil.isEmpty(userInfo)){
			throw new UsernameNotFoundException("用户不存在！");
		}
		//查询权限信息
		List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
		if(username.equals("18008406270")) {
			simpleGrantedAuthorities.add(new SimpleGrantedAuthority("admin"));
		}
		return new MyUserDetails(username, userInfo.getPassword(),userInfo.getName(), simpleGrantedAuthorities);
	}
	
	public class MyUserDetails extends User{
		
		private static final long serialVersionUID = 1L;
		
		private String name;
		
		public MyUserDetails(String username, String password, Collection<? extends GrantedAuthority> authorities) {
			super(username, password, authorities);
		}
		public MyUserDetails(String username, String password,String name, Collection<? extends GrantedAuthority> authorities) {
			super(username, password, authorities);
			this.name = name;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		
	}
}
